#!/usr/bin/env node
import readline from "readline";
import figlet from "figlet";
import inquirer from "inquirer";
import ora from "ora";
import clone from "git-clone";
import chalk from "chalk";

const outStream = process.stdout;

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

readline.cursorTo(outStream, 0, 0);
readline.clearScreenDown(outStream);

const error = chalk.bold.red;
const warning = chalk.hex("#FFA500"); // Orange color

const templateMap = {
  "wscc-web": "https://gitee.com/wsccfbh/wscc_web.git",
  "wscc-node": "https://gitee.com/wsccfbh/backend_template_node.git",
  "wscc-spring-boot": "https://gitee.com/wsccfbh/springBoot_test_admin.git",
  "wscc-cli": "https://gitee.com/wsccfbh/wscc-cli.git",
};

inquirer
  .prompt([
    {
      type: "list", // 此处可以 替换成rawlist试试看
      message: "请选择一个项目模板：",
      name: "template",
      default: "wscc-web",
      choices: Object.keys(templateMap),
    },
    {
      type: "input", // 类型
      name: "projectName", // 字段名称，在then里可以打印出来
      message: "projectName:", // 提示信息
    },
  ])
  .then((answers) => {
    console.log(chalk.blue("项目名称"), warning(answers.projectName));
    figlet("wscc ! !", function (err, data) {
      if (err) {
        console.log(error("Something went wrong...!"));
        console.dir(err);
        return;
      }

      const spinner = ora("Loading unicorns").start();
      spinner.color = "yellow";
      spinner.text = "Loading rainbows";

      clone(templateMap[answers.template], answers.projectName, (err) => {
        if (err) {
          spinner.fail(warning(answers.projectName) + error(" 项目创建失败"));
          return console.log(error(err));
        }
        spinner.succeed(warning(answers.projectName) + " 项目创建成功");
        console.log(chalk.green(data));
      });
      rl.close();
    }); // 与prompt的name字段对应
  })
  .catch((error) => {
    if (error.isTtyError) {
      // Prompt couldn't be rendered in the current environment
    } else {
      // Something else went wrong
    }
  });
